package com.wg.es.utils;

import com.wg.es.job.PreJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * Created by xiaoq on 2019-05-13 09:55.
 */
@Component
public class PreUtil implements ApplicationListener<ContextRefreshedEvent> {
    static SchedulerFactory schedulerFactory = new StdSchedulerFactory();


    private static void runJob() throws Exception {
        Scheduler scheduler = schedulerFactory.getScheduler();
        // 2、创建JobDetail实例，并与PrintWordsJob类绑定(Job执行内容)
        JobDetail jobDetail = JobBuilder.newJob(PreJob.class).build();
        // 3、构建Trigger实例,每隔1s执行一次
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1")
                .startNow()//立即生效
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(1)//每隔1s执行一次
                        .repeatForever()).build();//一直执行

        //4、执行
        scheduler.scheduleJob(jobDetail, trigger);
        System.out.println("--------scheduler start ! ------------");
        scheduler.start();
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            PreJob.await();
            System.out.println("scheduler wake up");
            runJob();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
